package com.ai.wxy.spring.storm.test.drpc;

import lombok.extern.slf4j.Slf4j;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.List;
import java.util.Map;

/**
 * 获取url转发的人员
 *
 * @author 石头
 * @Date 2019/12/18
 * @Version 1.0
 **/
@Slf4j
public class GetTweetersBolt extends BaseRichBolt{
    private OutputCollector collector;
    @Override
    public void prepare(Map<String, Object> stormConf, TopologyContext context, OutputCollector collector) {
        this.collector = collector;
    }

    @Override
    public void execute(Tuple tuple) {
        try {
            Object requestId = tuple.getValue(0);
            String url = tuple.getString(1);

            String urlId = getUrlId(url);

            if (urlId == null){
                return;
            }
            List<String> tweetters = TiwtterReachTopology.TWEETERS_DB.get(urlId);
            if (tweetters == null){
                return;
            }

            for (String teewtter : tweetters) {
                // 发送消息必须携带 Tuple，用于异常处理
                collector.emit(tuple, new Values(requestId, teewtter));
            }
        }finally {
            //如果使用BaseRichBolt 必须手动提交Ack / Fail
            //如果BaseBasicBolt，ack 自动调用的，这里必须注意，否则导致 Bolt 如果return 时，
            //下一个Blot无法获取数据
            collector.ack(tuple);
        }
    }
    private String getUrlId(String url) {
        for (Map.Entry<String, String> entry : TiwtterReachTopology.URLS_DB.entrySet()) {
            if (entry.getValue().equalsIgnoreCase(url)) {
                return entry.getKey();
            }
        }
        return null;
    }
    @Override
    public void declareOutputFields(OutputFieldsDeclarer declarer) {
        declarer.declare(new Fields("Id", "Tweetter"));
    }
}
